<?php
include('gamebank/nusoap.php');

class CreditController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}
	/*Json autocomplete Create.php*/
	public function actionSuggestPerson() {
		$criteria = new CDbCriteria;
		$criteria->select = array('id', 'username');
	
		$criteria->addSearchCondition('username',  strtoupper( $_GET['term']) ) ;
		$criteria->limit = 15;
		$data = User::model()->findAll($criteria);
	
		$arr = array();
	
		foreach ($data as $item) {
			 
			$arr[] = array(
					'id' => $item->id,
					'value' => $item->username,
					'label' => $item->username,
			);
		}
	
		echo CJSON::encode($arr);
	
	}
	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
/*	public function json($term='')
	{
		$users=User::model()->findAll();
				//$crit->condition='project_id = '.$_SESSION['project_id'].' ';
		if($term) $users->condition= "profile.lastname LIKE '".$term."%' ";
		$users->with=array('profile'=>array('select'=>'username'));
		$users->order='profile.username';
		foreach(User::model()->findAll($users) as $user)
		{
			$users1[] = array(
					'id'=>$user->id,
					'label'=>$user->name2,
			);
		}
		
		echo CJSON::encode(array('users'=>$users1));
		
	}*/
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view','lrsuccessfull'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update', 'napcredit','naplr', 'napthecao', 'chuyenkhoannganhang','kiemtrataikhoan','SuggestPerson', 'history'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}
	
	public function actionNapTheCao(){
		$history=new CActiveDataProvider('Chitietnapcredit',array('id'=>UserUtils::getUserId()));
		//$history = Chitietnapcredit::model()->findByAttributes(array('idcredit'=> UserUtils::getUserId()));
		if(isset($_POST['lstTelco']) && isset( $_POST['txtCode']) && isset($_POST['txtSeri'])){
			$telco = $_POST['lstTelco'];
			$code = $_POST['txtCode'];
			$seri = $_POST['txtSeri'];
			$strTemp = CCounterUtils::getinputcounter();
			$gamebank_account = "phongatt";
	/*	echo $gamebank_account ; die(); */
			$client = new nusoap_client("http://pay.gamebank.vn/service/cardServiceV2.php/?wsdl",true);
		
			$result = $client->call("creditCard",array("seri"=>$seri,"code"=> $code,"cardtype"=> $telco, "gamebank_account"=>$gamebank_account));
			/*print_r($result);die();*/
			/*print_r($result);*/
			if($result[0] >= 10000)
			{
				$chitiet = Creditdao::napTheCao(Yii::app()->user->getId(), $result[0]);
				$user = User::model()->findByPK(Yii::app()->user->getId()->id);
				EmailUtils::sendemailCreditChange($chitiet, $user);
				$message = 'Quí khách đã nạp thành công mệnh giá thẻ cào '. $result[0]. ' vào tài khoản.';
				$this->render('napcreditthanhcong', array('message'=>$message));
			}
			else
			{
				//$message = 'Quí khách đã nạp thành công mệnh giá thẻ cào 10000 vào tài khoản.';
				//$this->render('napcreditthanhcong', array('message'=>$message));
				$message = 'Thao tác không thành công, vui lòng liên hệ admin để được hổ trợ trực tuyến';
				$this->render('napcreditkhongthanhcong', array('message'=>$message));
			}
		
		}else{	
			
			
			$this->render('napthecao',array('history'=>$history));
		}
	}
	
	public function actionChuyenkhoannganhang(){
		$this->render('chuyenkhoannganhang');
	}
	
	public function actionHistory($id){
		$history = Creditdao::HistoryNapCre($id);
		$this->render('_history',$history);
	}
	
	public function actionNaplr(){
		$this->render('naplr');
	}
	
	public function actionlrsuccessfull(){
		
		
		$user = User::model()->findByPK($_POST['order_id']);
		if($user != null){
			$model = Creditdao::napCredit_LR($user, $_POST['lr_amnt'],$_POST['lr_timestamp']);
			$this->render('lrsuccessfull', array('model'=>$model));
		}
		
		
/*		
		<input type="hidden" name="lr_paidto" value="U123456">
<input type="hidden" name="lr_paidby" value="U789">
<input type="hidden" name="lr_amnt" value="12.34">
<input type="hidden" name="lr_fee_amnt" value="0">
<input type="hidden" name="lr_currency" value="LRUSD">
<input type="hidden" name="lr_transfer" value="4456778335534">
<input type="hidden" name="lr_store" value="MyStore">
<input type="hidden" name="lr_timestamp" value="2007-25-03 10:45:55">
<!-- baggage fields set by the Merchant -->
<input type="hidden" name="track_id" value="166337678784">
<input type="hidden" name="order_id" value="O7993547">

		echo 'nap lr thanh cong';
		*/
	}
	
	public function actionlrfailse(){
		echo 'nap lr that bai';
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Credit;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
		$model->unsetAttributes();
		if(isset($_POST['Credit']))
		{
			$model->attributes=$_POST['Credit'];
			//print_r($model->attributes);
			//die();
			$user = User::model()->findByAttributes(array('username'=>$model->username));
			$model->iduser = $user->id;
			$chitiet = Creditdao::addCredit($user, $model->sodu);
			EmailUtils::sendemailCreditChange($chitiet,$user);
			$this->redirect(array('admin'));
		}
		$var =Userdao::getList();
		$data['users'] = CHtml::listData($var, "id", "username");
		$data['model'] = $model;
		$this->render('create',$data);
	}
	
	public function actionNapCredit()
	{
		$model=new Credit;
		
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Credit']))
		{
			$model->attributes=$_POST['Credit'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('napcredit',array(
			'model'=>$model,
				
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Credit']))
		{
			$model->attributes=$_POST['Credit'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		
		$dataProvider=new CActiveDataProvider('Credit');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
				
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Credit('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Credit']))
			$model->attributes=$_GET['Credit'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Credit::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='credit-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	
	public function actionKiemTraTaiKhoan(){
		$credit = Credit::model()->findByAttributes(array('iduser'=> UserUtils::getUserId()));
		$this->render('kiemtrataikhoan', array('model'=>$credit));
	}
	public function actionLichSuNapCredit()
	{
		$credit = Credit::model()->findByAttributes(array('iduser'=> UserUtils::getUserId()));
		$this->render('kiemtrataikhoan', array('model'=>$credit));
		
	}
	
	
		
	

}
